package com.yjz.study.adapter.detail

import android.graphics.Color
import android.text.TextUtils
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.core.view.ViewCompat
import androidx.recyclerview.widget.RecyclerView
import com.yjz.common.extend.loadUrl
import com.yjz.study.http.entity.res.SliderImage
import com.yjz.ui.recycler.item.HiDataItem
import com.yjz.ui.recycler.item.HiViewHolder

/**
 *作用 : 商品详情 商品相册
 *作者 : yjz
 *时间 : 2025/5/15 15:35
 */
class GoodsDetailGalleryItem(val sliderImage: SliderImage) : HiDataItem<SliderImage, HiViewHolder>() {
    private var parentWidth: Int = 0

    override fun onBindData(holder: HiViewHolder, position: Int) {
        val imageView = holder.itemView as ImageView
        if (!TextUtils.isEmpty(sliderImage.url)) {
            imageView.loadUrl(sliderImage.url) { drawable ->
                val drawableWidth = drawable.intrinsicWidth
                val drawableHeight = drawable.intrinsicHeight

                val params = imageView.layoutParams ?: RecyclerView.LayoutParams(
                    parentWidth,
                    RecyclerView.LayoutParams.WRAP_CONTENT
                )
                params.width = parentWidth
                params.height = (drawableHeight / (drawableWidth * 1.0f / parentWidth)).toInt()
                imageView.layoutParams = params
                ViewCompat.setBackground(imageView, drawable)
            }
        }
    }

    override fun getItemView(parent: ViewGroup): View? {
        val imageView = ImageView(parent.context)
        imageView.scaleType = ImageView.ScaleType.CENTER_CROP
        imageView.setBackgroundColor(Color.WHITE)
        return imageView
    }

    override fun onViewAttachedToWindow(holder: HiViewHolder) {
        super.onViewAttachedToWindow(holder)
        parentWidth = (holder.itemView.parent as ViewGroup).measuredWidth
        val params = holder.itemView.layoutParams
        if (params.width != parentWidth) {
            params.width = parentWidth
            params.height = parentWidth
            holder.itemView.layoutParams = params
        }
    }

}